const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin'); //css js 打包成内联方式
const path = require('path');

module.exports = () => {
	const __DEV__ = process.env.NODE_ENV == 'development' || process.env.NODE_ENV == 'test';
	return {
		mode: __DEV__ ? 'development' : 'production', //打包模式
		entry: __dirname + '/src/main.js', //入口文件
		output: {
			path: __dirname + '/dist', //打包文件的路径
			filename: '[name].js?[hash:6]', //文件名称
		},
		devtool: __DEV__ ? 'source-map' : '', //sourcemap的模式
		devServer: {
			//本地服务配置
			contentBase: './',
			port: 2222,
			// host: '192.168.1.114',
		},
		module: {
			rules: [
				{
					test: /\.bundle\.js$/,
					loader: 'bundle-loader',
					include: /page/,
					options: {
						lazy: true,
						name: '[name]',
					},
				},
				{
					test: /\.(js|jsx)$/,
					exclude: /node_modules/,
					loader: 'babel-loader',
				},
				{
					test: /\.s?css$/,
					use: [
						__DEV__
							? 'style-loader'
							: {
									loader: MiniCssExtractPlugin.loader,
									options: {
										hmr: __DEV__,
									},
							  },
						'css-loader',
						{
							loader: 'postcss-loader',
							options: {
								plugins: [
									require('autoprefixer')(),
									require('postcss-adaptive-exclude')({
										remUnit: 75,
										exclude: /node_modules/,
									}),
								],
							},
						},
						'sass-loader',
					],
				},
			],
		},
		plugins: [
			new webpack.DefinePlugin({
				//配置全局变量
				__DEV__: __DEV__,
			}),
			new CleanWebpackPlugin(['dist']), //清楚dist目录
			new MiniCssExtractPlugin({
				//css文件打包
				filename: __DEV__ ? '[name].css' : '[name].[hash].css',
				chunkFilename: __DEV__ ? '[id].css' : '[id].[hash].css',
			}),
			new htmlWebpackPlugin({
				//html模板
				title: 'my-app',
				template: './index.ejs',
				filename: 'index.html',
				inject: true,
				inlineSource: '.(js|css)$',
				minify: __DEV__
					? false
					: {
							removeComments: true, //清楚注释
							collapseWhitespace: true, //清楚空格
							minifyCSS: true, //压缩html样式
							minifyJS: true, //压缩html js
					  },
			}),
			new HtmlWebpackInlineSourcePlugin(),
		],
		resolve: {
			//引入的模块 配置
			extensions: ['.js', '.jsx', '.ts', '.tsx'],
			modules: [path.resolve('./src'), path.resolve('./node_modules')],
		},
	};
};
